/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.gaspar.utils;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author icorrea
 */
public class JNDIUtil {

    static InitialContext ctx;

    private JNDIUtil() {
    }

    private static InitialContext getContext() {
        if (ctx == null) {
            try {
                Properties props = new Properties();
                props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
                props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
                props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
                props.put(InitialContext.PROVIDER_URL, "iiop://localhost");
                ctx = new InitialContext(props);

            } catch (NamingException e) {
                throw new RuntimeException("Nao foi possivel pegar o initial context", e);
            }
        }
        return ctx;
    }

    /**
     *
     * @param <T>
     *            Tipo da entidade a a ser retornada
     * @param clazz
     *            Tipo da classe a ser retornada
     * @param name
     *            Nome Jndi do EJB a ser encontrado, e.g. XxxFacade/local ou, XxxFacade/Remote
     * @return 
     */
    @SuppressWarnings("unchecked")
    public static <T> T lookup(Class<T> clazz, String name) {
        final InitialContext ctx2 = getContext();
        try {
            final Object object = ctx2.lookup(name);
            if (clazz.isAssignableFrom(object.getClass())) {
                return (T) object;
            } else {
                throw new RuntimeException(String.format(
                        "Classe encontrada: %s nao pode ser atribuido ao tipo : %s",
                        object.getClass(), clazz));
            }

        } catch (NamingException e) {
            throw new RuntimeException(String.format(
                    "Nao foi possivel encontrar o EJB (%s)", clazz.getName()), e);
        }
    }
}
